//
//  DestinationViewController.m
//  OurTourism
//
//  Created by dllo on 15/11/23.
//  Copyright © 2015年 Devil_Coming. All rights reserved.
//

#import "DestinationViewController.h"
#import "BaseClassViewController.h"
#import "Header.h"
#import "YBDestinationModel.h"
#import "YBSearchCollectionViewController.h"
#import "YBDestinationTableViewcell.h"
#import "YBStoryTableViewCell.h"
#import "YBStoryitemCollectionViewCell.h"
#import "YBWebViewController.h"
#import "YBSecViewController.h"
#import "YBStorydetialViewController.h"
#import "YBTraveldetialViewController.h"
#import "MZRecommendModel.h"
#import "YBscrollview.h"

@interface DestinationViewController ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UISearchBarDelegate,jumpToWebView>
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, retain)UIView *headerViewTop;
@property (nonatomic, strong)UICollectionView *collectionView;
@property (nonatomic, assign)NSInteger height; // 接受每个游记cell行高
@property (nonatomic, strong)NSMutableArray *dataArr; //推荐首页总数组
@property (nonatomic, strong)NSMutableArray *ScrollViewDataArr;
@property (nonatomic, strong)NSMutableArray *storyArr;
@property (nonatomic, strong)NSMutableArray *modelStoryDataArr; //转化为model的story数组
@property (nonatomic, strong)NSMutableArray *modelUserDataArr; // 转化为model的story中的user数组
@property (nonatomic, strong)NSMutableArray *modelTravelDataArr;
@property (nonatomic, strong)NSMutableArray *modelTravelUserArr;
@property (nonatomic, strong)NSMutableArray *modelDetailStoryArr;//转化为对象的故事详情数组
@property (nonatomic, strong)NSNumber *next_start; //下一页数据
@property (nonatomic, strong)UISearchBar *searchBar;
@property (nonatomic, strong)NSMutableArray *modelSearchArr;
@property (nonatomic, strong)NSMutableArray *modelSearchElementsArr;
@property (nonatomic, strong)UIView *nightView;
@property (nonatomic, strong)UIView *headerView;
@property (nonatomic, strong)MBProgressHUD *hud;
@property (nonatomic, retain)YBscrollview *headerScrollView;
@end

@implementation DestinationViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.tableView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 49);
  
        [super viewWillAppear:animated];
        self.navigationController.navigationBar.hidden = NO;
   
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithRed:250 / 255. green:246 / 255. blue:232 / 255. alpha:1];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:62 / 255. green:176 / 255. blue:192 / 255. alpha:1];
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    
    
    [self loadMBProgress];
    //获取数据
    [self getData];
}
// 小菊花
- (void)loadMBProgress
{
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    
    self.hud.dimBackground = NO;
    //设置对话框文字
    self.hud.labelText = @"loading";
    self.hud.minShowTime = 50;
    self.hud.activityIndicatorColor = [UIColor whiteColor];
    self.hud.labelColor = [UIColor whiteColor];
    
    [self.view addSubview:self.hud];
    [self.hud showAnimated:YES whileExecutingBlock:^{
        //对话框显示时需要执行的操作
        sleep(1);
    } completionBlock:^{
        //操作执行完后取消对话框
        [self.hud removeFromSuperview];
        self.hud = nil;
    }];
    
}
#pragma mark - 获取推荐首页数据
- (void)getData
{
    NSString *url = @"http://api.breadtrip.com/v2/index/?lat=38.8802706535603&lng=121.54089204778&sign=dfcaa3638dd2a27e24a726ba2d2fd3cd";
    [MZNetHandle getUrl:url cookie:nil result:^(id result) {
        //下一页id
        self.next_start = result[@"data"][@"next_start"];
        //首页总数据
        self.dataArr = result[@"data"][@"elements"];
        self.ScrollViewDataArr = [NSMutableArray array];
        //轮播图数组
        self.ScrollViewDataArr = [YBDestinationModel transformWithArray:[self.dataArr[0] objectForKey:@"data"][0]];
        
        
        //搜索页数据
        self.modelSearchArr = [YBDestinationModel transformWithArray:result[@"data"][@"search_data"]];
        self.modelSearchElementsArr = [NSMutableArray array];
        for (NSMutableDictionary *dic in result[@"data"][@"search_data"] ) {
            [self.modelSearchElementsArr addObject: [MZRecommendModel transformWithArray:dic[@"elements"]]];
        }

        //story数据
        //创建一个数组 用来存放所有type == 10的字典
        NSMutableArray *typeArr = [NSMutableArray array];
        for (NSDictionary *dic in self.dataArr) {
            
            NSString *type = [NSString stringWithFormat:@"%@", dic[@"type"]];
            if ([type isEqualToString:@"10"]) {
                [typeArr addObject:dic];
            }
        }
        //创建一个数组 用来接收四个view的数据
        NSMutableArray *typeDataArr = [NSMutableArray array];
        for (NSDictionary *dic in typeArr) {
            [typeDataArr addObject: dic[@"data"][0]];
        }
        //创建一个数组 用来接收四个view中user信息的数据
        NSMutableArray *typeUserArr = [NSMutableArray array];
        for (NSDictionary *dic in typeDataArr) {
            [ typeUserArr addObject: dic[@"user"]];
        }
        self.modelStoryDataArr = [YBDestinationModel transformWithArray:typeDataArr];
        self.modelUserDataArr = [YBDestinationModel transformWithArray:typeUserArr];

//游记数据
        //创建一个数组 用来存放所有type == 4的字典
        NSMutableArray *travelArr = [NSMutableArray array];
        for (NSDictionary *dic in self.dataArr) {
            
            NSString *type = [NSString stringWithFormat:@"%@", dic[@"type"]];
            if ([type isEqualToString:@"4"]) {
                [travelArr addObject:dic];
            }
        }
        //创建一个数组 用来接收view的数据
        NSMutableArray *travelDataArr = [NSMutableArray array];
        for (NSDictionary *dic in travelArr) {
            [travelDataArr addObject: dic[@"data"][0]];
        }
        //创建一个数组 用来接收四个view中user信息的数据
        NSMutableArray *travelUserArr = [NSMutableArray array];
        for (NSDictionary *dic in travelDataArr) {
            [travelUserArr addObject: dic[@"user"]];
        }
        self.modelTravelDataArr = [YBDestinationModel transformWithArray:travelDataArr];
        self.modelTravelUserArr = [YBDestinationModel transformWithArray:travelUserArr];
        

        [self SearchBar];
        if (self.tableView == nil) {
            //创建tableView
            [self createMainTableView];
        }
        else
        {
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
        }
        [self.hud removeFromSuperview];
    }];
}

- (void)createMainTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 49) style:UITableViewStyleGrouped];
      [self createHeaderScrollView];
    self.tableView.scrollsToTop = YES;
    self.tableView.delegate = self;
    self.tableView.dataSource =self;
    [self.view addSubview:self.tableView];
    [self MJRefresh];
    
}
#pragma mark - MJ刷新
- (void)MJRefresh
{
    //MJ下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        [self getData];
    }];
    //上拉加载
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        NSString *url = [ NSString stringWithFormat:@"http://api.breadtrip.com/v2/index/?next_start=%@", self.next_start];
        [MZNetHandle getUrl:url cookie:nil result:^(id result) {
            NSMutableDictionary *dic = result;
            //接收总字典
            NSMutableDictionary *tempDic = result;
            //下一页id
            self.next_start = tempDic[@"data"][@"next_start"];
            NSMutableArray *tempArr =  dic[@"data"][@"elements"];
            //创建一个数组 用来存放所有type == 4的字典
            NSMutableArray *travelArr = [NSMutableArray array];
            for (NSDictionary *dic in tempArr) {
                
                NSString *type = [NSString stringWithFormat:@"%@", dic[@"type"]];
                if ([type isEqualToString:@"4"]) {
                    [travelArr addObject:dic];
                }
            }
            //创建一个数组 用来接收view的数据
            NSMutableArray *travelDataArr = [NSMutableArray array];
            for (NSDictionary *dic in travelArr) {
                [ travelDataArr addObject: dic[@"data"][0]];
            }
            //把之后页面的对象数组中的对象 加到原对象数组中
            [self.modelTravelDataArr addObjectsFromArray:[YBDestinationModel transformWithArray:travelDataArr]];
            //user数据加到原对象数组中
            NSMutableArray *userDataArr = [NSMutableArray array];
            for (NSDictionary *dic in tempArr) {
                NSMutableDictionary *tempDic = dic[@"data"][0][@"user"];
                [userDataArr addObject:tempDic];
            }
            [self.modelTravelUserArr addObjectsFromArray:[YBDestinationModel transformWithArray:userDataArr]];
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
        }];
    }];
}

- (void)createHeaderScrollView
{
    self.headerViewTop = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 200)];
    self.tableView.tableHeaderView = self.headerViewTop;
    self.headerScrollView = [[YBscrollview alloc]initWithFrame:self.headerViewTop.frame dataArr:self.ScrollViewDataArr];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //设置代理人
    self.headerScrollView.delegate = self;
    [self.headerViewTop addSubview:self.headerScrollView];
}
#pragma mark - 轮播图实现协议方法
- (void)jumptoWebView:(NSString *)str
{
    YBWebViewController *webView = [[YBWebViewController alloc]init];
     webView.urlStr = str;
     webView.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:webView animated:YES];
}

#pragma mark - 创建searchBar
- (void)SearchBar
{
    UIButton *titLeView = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, WIDTH - 100, 30)];
    [titLeView addTarget:self action:@selector(pushToSearch) forControlEvents:UIControlEventTouchUpInside];
    //titLeView.backgroundColor = [UIColor redColor];
    self.navigationItem.titleView = titLeView;
  //  self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"dd"] style:UIBarButtonItemStylePlain target:self action:@selector(rightAction)];
    // 初始化
    self.searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, WIDTH - 100, 30)];
    // 设置代理
    self.searchBar.delegate = self;
    //类型
    [self.searchBar setBarStyle:UIBarStyleDefault];
    //提示文本
    self.searchBar.placeholder = @"搜索目的地  游记...";
    //键盘类型
    [self.searchBar setKeyboardType:UIKeyboardTypeDefault];
    //视图剪切
    self.searchBar.layer.masksToBounds = YES;
    self.searchBar.layer.cornerRadius = 10;
    
    //关闭用户交互
    self.searchBar.userInteractionEnabled = NO;
    [titLeView addSubview:self.searchBar];
    
}
#pragma mark - 搜索按钮触发方法

- (void)rightAction
{
    NSLog(@"附近");
}

// 跳转下一页
- (void)pushToSearch
{
    YBSearchCollectionViewController *search = [[YBSearchCollectionViewController alloc]init];
    search.hidesBottomBarWhenPushed = YES;
    search.modelSearchArr = self.modelSearchArr;
    search.modelSearchElementsArr = self.modelSearchElementsArr;
    [self.navigationController pushViewController:search animated:YES];
}
#pragma mark - 分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

#pragma mark - 分区头部高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 54;
}
#pragma mark - 分区头view
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *viewTitle = [[UIView alloc]init];
    
    viewTitle.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];

    UILabel *blueLable = [[UILabel alloc]initWithFrame:CGRectMake(10, 20 , 5, 25)];
    blueLable.backgroundColor = [UIColor colorWithRed:0.35 green:0.73 blue:0.78 alpha:1];
    blueLable.layer.masksToBounds = YES;
    blueLable.layer.cornerRadius = 2;

    UILabel *titleLable = [[UILabel alloc]initWithFrame:CGRectMake(25, blueLable.frame.origin.y, WIDTH - 25 , blueLable.frame.size.height)];
    titleLable.textColor = [UIColor darkGrayColor];
    titleLable.font = [UIFont fontWithName:@"Arial-Bold" size:15];
    
    //全部按钮
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    btn.frame =CGRectMake(WIDTH - 90, blueLable.frame.origin.y, 90, blueLable.frame.size.height);
    
    [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    [btn setTitle:@"全部" forState:UIControlStateNormal];
    
    [btn addTarget:self action:@selector(MorePageAction) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIImageView *imgAllRight = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"dd"]];
    imgAllRight.frame = CGRectMake(65, 3, 20, btn.frame.size.height - 5);
    
    if (section == 0) {
        titleLable.text = self.dataArr[1][@"data"][0][@"title"];
        [viewTitle addSubview:btn];
        [btn addSubview:imgAllRight];
    }else
    {
        titleLable.text = self.dataArr[6][@"data"][0][@"title"];
    }
     [viewTitle addSubview:titleLable];
     [viewTitle addSubview:blueLable];
    return viewTitle;
}

#pragma mark - 更多 故事
- (void)MorePageAction
{
    YBSecViewController *sec = [[YBSecViewController alloc] init];
    [self.navigationController pushViewController:sec animated:YES];
}


#pragma mark - tableView  分行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    else
    {
        return self.modelTravelDataArr.count ;
    }
}





#pragma mark - tableView 数据
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        YBStoryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"story"];
        if (!cell) {
            cell = [[YBStoryTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"story"];
        }
        cell.delegate = self;
        cell.dataSource = self;
        return cell;
    }
    else
    {
        YBDestinationTableViewcell *cell = [tableView dequeueReusableCellWithIdentifier:@"travel"];
        if (!cell) {
            cell = [[YBDestinationTableViewcell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"travel"];
        }
        cell.travelModel = self.modelTravelDataArr[indexPath.row];
        cell.travelUserModel = self.modelTravelUserArr[indexPath.row] ;
        cell.backgroundColor =  [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
        return cell;
    }
}

#pragma mark - tableView行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 500;
    }
    else{
        return 250;
    }
}

#pragma mark - tableView点击方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    //游记分区
    if (indexPath.section == 1) {
        YBTraveldetialViewController *travelNotes = [[YBTraveldetialViewController alloc]init];
        travelNotes.travelNotesModel = self.modelTravelDataArr[indexPath.row];
        travelNotes.valueId = [self.modelTravelDataArr[indexPath.row] id];
        travelNotes.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:travelNotes animated:YES];
    }
}

#pragma mark - 协议方法 item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 4;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    YBStoryitemCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"StoryItemitem" forIndexPath:indexPath];
    cell.recommendModel = self.modelStoryDataArr[indexPath.item];
    cell.userModel = self.modelUserDataArr[indexPath.item];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
        YBStorydetialViewController *storyDetail = [[YBStorydetialViewController alloc]init];
       storyDetail.spot_id = ((YBDestinationModel *)self.modelStoryDataArr[indexPath.item]).spot_id;
    
    storyDetail.recommendModel = self.modelStoryDataArr[indexPath.item];
    
     [self presentViewController:storyDetail animated:YES completion:^{
     }];
    
    
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
